import { getTableData } from "@/service/api.js";
import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";

export const useTable = create(
  persist(
    (set, get) => ({
      title: "我是table状态管理",
      tableData: [],
      storageData: [],
      setState: (payload) => {
        let obj = {};
        Object.keys(payload).forEach((key) => {
          obj[key] = payload[key];
        });
        set(obj);
      },
      increase: () => {
        const newArr = get().tableData;
        newArr.push({
          name: "肖明华",
          age: 20,
        });
        set({ tableData: newArr });
      },
      fetchGetTableData: async (params) => {
        const res = await getTableData(params);
        if (res && res?.code === 200) {
          set({
            tableData: res?.data,
          });
        } else {
          set({
            tableData: [],
          });
        }
      },
    }),
    {
      name: "table-storage",
      storage: createJSONStorage(() => localStorage),
      partialize: (state) => ({
        //partialize手动控制缓存哪些属性   不设置则默认全部state
        tableData: state.tableData,
      }),
    },
  ),
);
